public without sharing class InvoiceAccountController {
	
	public string searchJson {get; set;}
	public String dataJson {get;private set;}
	public String saveJson {get; set;}

	public String companyJson {get; private set;}
	public Map<String,String> companyMap ;

	public Boolean isSuccess {get; private set;}
	public String msg {get; private set;}
    public class ControllerException extends Exception {}

	//开票客户合并对照表
    public InvoiceAccountController() {
    	

    }
    //初始化
    public void init(){
    	companyMap = ImportObject.getPicklistValues('InoviceAccount__c', 'Company__c', true);
        companyJson = JSON.serialize( companyMap);
    }

   /* public void getDetails(){
    	List<IAccountBean> tmp = new List<IAccountBean>();
    	for(InoviceAccount__c ia :[select Id , CombineAccount__c,CombineAccount__r.Name ,CombineAccount__r.AccountNumber,
    		Account__r.AccountNumber,Account__r.Name ,Company__c,Account__c from InoviceAccount__c limit 200]){
    		tmp.add(new IAccountBean(ia,companyMap));
    	}
    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

    }*/
    //删除
    @RemoteAction
    public static void deleteRecord(List<String> records ){

    	delete [select Id from InoviceAccount__c where Id in: records];

    }
    //导入
    @RemoteAction
    public  static List<IAccountBean>  matchAccount(String  data  ){

    	List<Object> datas =(List<Object>) JSON.deserializeUntyped(data);
    	Map<String,Map<String,String>> allMap = new Map<String,Map<String,String>>();
    	Set<String>  accCodes= new Set<String>();
    	for(Object o : datas){
    		Map<String,Object> mo = (Map<String,Object>)o;
    		Map<String ,String > mmap = new Map<String,String>();
            try{

                mmap.put('accId', Id.valueOf(String.valueOf(mo.get('accId'))));
                mmap.put('combineaccId', Id.valueOf(String.valueOf(mo.get('combineaccId'))));
                mmap.put('companycode', String.valueOf(mo.get('companycode')));

                if(mmap.get('accId') !=  null )accCodes.add(mmap.get('accId'));
                if(mmap.get('combineaccId') !=  null )accCodes.add(mmap.get('combineaccId'));

                allMap.put(mmap.get('accId')+'-'+mmap.get('combineaccId')+'-'+mmap.get('companycode'), mmap);

            }catch(Exception e ){
                continue;
            }
    		
    	}
    	datas.clear();
    	Map<String,Account> accMap = new Map<String,Account>();
    	for(Account acc : [select Id,Name ,AccountNumber from Account where Id in : accCodes]){

    		accMap.put(acc.Id, acc);
    	}
    	accCodes.clear();
    	List<IAccountBean> tmp = new List<IAccountBean>();
    	for(String key : allMap.keySet()){

    		tmp.add(new IAccountBean(allMap.get(key),accMap.get(allMap.get(key).get('accId')),accMap.get(allMap.get(key).get('combineaccId'))));
    	}
    	return tmp ;



    }
    //查询
    public void search(){

    	Map<String ,Object>searchMap = (Map<String ,Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(searchJson,'UTF-8'));

    	String sql = 'select Id , CombineAccount__c,CombineAccount__r.Name ,CombineAccount__r.AccountNumber,'+
    		'Account__r.AccountNumber,Account__r.Name ,Company__c,Account__c from InoviceAccount__c where Id != null ';

    	if(String.isBlank(String.valueOf(searchMap.get('name'))) == false)sql += ' and Account__r.Name like \'%'+String.valueOf(searchMap.get('name'))+'%\'';
      
      	if(String.isBlank(String.valueOf(searchMap.get('code'))) == false)sql += ' and Account__r.AccountNumber = \''+String.valueOf(searchMap.get('code'))+'\'';
      
      	if(String.isBlank(String.valueOf(searchMap.get('combinename'))) == false)sql += ' and CombineAccount__r.Name like \'%'+String.valueOf(searchMap.get('combinename'))+'%\'';
      
       	if(String.isBlank(String.valueOf(searchMap.get('combinecode'))) == false)sql += ' and CombineAccount__r.AccountNumber = \''+String.valueOf(searchMap.get('combinecode'))+'\'';
      
        if(String.isBlank(String.valueOf(searchMap.get('company'))) == false)sql += ' and Company__c = \''+String.valueOf(searchMap.get('company'))+'\'';

        sql += ' limit 200 ';
	    	System.debug('InvoiceAccountController==>'+sql);
        List<IAccountBean> tmp = new List<IAccountBean>();
        for(InoviceAccount__c ia :Database.query(sql)){
        		tmp.add(new IAccountBean(ia,companyMap));
    	}
    	dataJson = EncodingUtil.urlEncode(JSON.serialize(tmp), 'UTF-8');

    }
    //保存
    public void save (){
    	msg = '';
    	List<InoviceAccount__c> iaList = new List<InoviceAccount__c>();
        List<InoviceAccount__c> iaeList = new List<InoviceAccount__c>();
    	try{

    		List<Object> saveList = (List<Object>)JSON.deserializeUntyped(EncodingUtil.urlDecode(saveJson,'UTF-8'));
	    	if(saveList.size() == 0)throw new ControllerException('没有数据!');
	    	for(Object o : saveList){

	    		Map<String ,Object> mo = (Map<String,Object>) o ; 
	    		InoviceAccount__c ia = new InoviceAccount__c();
	    		String rId = DataUtil.getStringValue(mo.get('recordId'));
	    		if(rId != null && rId.length() > 0 ) ia.Id = rId;

	    		ia.Account__c = DataUtil.getStringValue(mo.get('accId'));
	    		if(ia.Account__c == null || DataUtil.getStringValue(mo.get('accId')).length() == 0 )throw new ControllerException('客户名称必填!');
	    		ia.CombineAccount__c = DataUtil.getStringValue(mo.get('combineaccId'));
	    		if(ia.CombineAccount__c == null ||  DataUtil.getStringValue(mo.get('combineaccId')).length() == 0 )throw new ControllerException('合并客户名称必填!');
	    		
	    		ia.Company__c = DataUtil.getStringValue(mo.get('companycode'));

                ia.Only__c = ia.Account__c+''+ia.CombineAccount__c+''+ia.Company__c;
	    		  if(ia.Id == null )iaList.add(ia);
                   if(ia.Id != null )iaeList.add(ia);
	    	}
	    	System.debug('InvoiceAccountController==>'+iaList);


    	}catch(Exception e){
    		msg = e.getMessage();
    		return;
    	}

    	SavePoint sp = Database.setSavepoint();
    	try {
    		if(iaList.size() > 0 )upsert iaList Only__c;
            if(iaeList.size() > 0 ) update iaeList;
    	    isSuccess = true;
    	    msg = '保存成功!';
    	}catch (Exception e) {
    		Database.rollback(sp);
    	    isSuccess = false;
    	    msg = '保存失败!'+e.getMessage();
    	}
    	


    	
    }



    public void setNil(){
    	searchJson = '{}';
    	dataJson = '[]';
    	saveJson = '[]';
    }



    public class IAccountBean{

    	public String recordId ; 
    	public string name ;//客户名称
    	public string code ;//客户编码
    	public string accId;
    	public string  company ; //公司名称
    	public string companycode; //公司编码

    	public string combinename ; //合并客户名称
    	public string combinecode ;//合并客户编码
    	public string combineaccId;

    	public IAccountBean(InoviceAccount__c ia,Map<String,String> cMap  ){
    		recordId = ia.Id;
    		name = ia.Account__r.Name ; 
    		code = ia.Account__r.AccountNumber;
    		accId = ia.Account__c;
    		company = cMap.get(ia.Company__c);
    		companycode = ia.Company__c;
    		combinename = ia.CombineAccount__r.Name;
    		combinecode = ia.CombineAccount__r.AccountNumber;
    		combineaccId = ia.CombineAccount__c;
    	}

    	public IAccountBean(Map<String,String> d  ,Account  acc,Account combineacc   ){

    		companycode = d.get('companycode');
    		if(acc != null){
    			name = acc.Name;
    			accId = acc.Id;
    			code = acc.AccountNumber;
    		}
    		if(combineacc != null ){
    			combinename = combineacc.Name;
    			combinecode = combineacc.AccountNumber;
    			combineaccId = combineacc.Id ;
    		}
    	} 


    }
}